#include <time.h>
#include <mysql/mysql.h>
#include <string.h>
#include "shtml.h"
#include <stdarg.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <signal.h>
#include <errno.h>

#define BUFFER_SIZE 1024
static char host_name[BUFFER_SIZE];
static char user_name[BUFFER_SIZE];
static char password [BUFFER_SIZE];
static char db_name  [BUFFER_SIZE];

static int port_number;
static bool DEBUG=false;

#define LOCKFILE "/var/run/giavang.pid"
#define LOCKMODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
static MYSQL *conn;


int sleep_time = 600;
int giasp[][2]={{0,0},{0,0}};
int baogia=0;
bool isnew = false;

//For daemon start:
static bool STOP=false;
void call_for_exit(int s)
{
   STOP=true;
   printf("Stopping Giavang...\n");
}
//Doc file cau hinh
int after_equal(char * c){
	int i=0;
	for(;c[i]!='\0'&&c[i]!='=';i++);
	return ++i;
}
void trim(char * c)
{
    char buf[BUFFER_SIZE];
    char * start,*end;
    strcpy(buf,c);
    start=buf;
    while(isspace(*start)) start++;
    end=start;
    while(!isspace(*end)) end++;
    *end='\0';
    strcpy(c,start);
}
bool read_buf(char * buf,const char * key,char * value)
{
   if (strncmp(buf,key, strlen(key)) == 0)
    {
		strcpy(value, buf + after_equal(buf));
		trim(value);
		return 1;
   }
   return 0;
}
void read_int(char * buf,const char * key,int * value)
{
	char buf2[BUFFER_SIZE];
	if (read_buf(buf,key,buf2))
		sscanf(buf2, "%d", value);

}
void write_log(const char *fmt, ...)
{
	va_list         ap;
	char            buffer[4096];
	char times[20];
    struct tm *sTm;
    time_t now = time (0);
    sTm = gmtime (&now);
    strftime (times, sizeof(times), "%Y-%m-%d %H:%M:%S", sTm);

	sprintf(buffer,"/var/log/baogia.log");
	FILE *fp = fopen(buffer, "a+");
	if (fp==NULL)
    {
		 fprintf(stderr,"openfile error!\n");
		 system("pwd");
	}va_start(ap, fmt);
	vsprintf(buffer, fmt, ap);
	fprintf(fp,"%s \t %s\n",times,buffer);
	//if (DEBUG) printf("%s\n",buffer);
	va_end(ap);
	fclose(fp);

}

//Khoi tao mysql
bool init_mysql_conf()
{
	FILE *fp=NULL;
	char buf[BUFFER_SIZE];
	host_name[0]=0;
	user_name[0]=0;
	password[0]=0;
	db_name[0]=0;
	port_number=3306;

	fp = fopen("/etc/baogia.conf", "r");
	if(fp!=NULL)
    {
        while (fgets(buf, BUFFER_SIZE - 1, fp))
        {
            read_buf(buf,"F_HOST_NAME",host_name);
            read_buf(buf, "F_USER_NAME",user_name);
            read_buf(buf, "F_PASSWORD",password);
            read_buf(buf, "F_DB_NAME",db_name);
            read_int(buf , "F_PORT_NUMBER", &port_number);

        }
        write_log("Load file %s %s %s %s",host_name,user_name,password,db_name);
		return true;
	//	fclose(fp);
    }
    else
    {
        write_log("Cannot open file 'giavang.conf'");
        return false;
    }
}
bool executesql(const char * sql)
{
	if (mysql_real_query(conn,sql,strlen(sql)))
    {
		write_log("Error in sql %s:%s",sql,mysql_error(conn));
		sleep(20);
		conn=NULL;
		return false;
	}
	else
	    return true;
}

bool init_mysql() {
    if(conn==NULL)
    {
		conn=mysql_init(NULL);		// init the database connection
		/* connect the database */
		const char timeout=30;
		mysql_options(conn,MYSQL_OPT_CONNECT_TIMEOUT,&timeout);

		if(!mysql_real_connect(conn,host_name,user_name,password,db_name,port_number,0,0))
        {
			write_log("Error init mysql with host=%s,user=%s,pass=%s,db=%s: %s",host_name,user_name,password,db_name,mysql_error(conn));
			sleep(20);
			return false;
		}
	}
	if (!executesql("set names utf8"))
    {
        return false;
    }

	return true;
}
//Xu li chinh

//For daemon:
int lockfile(int fd)
{
	struct flock fl;
	fl.l_type = F_WRLCK;
	fl.l_start = 0;
	fl.l_whence = SEEK_SET;
	fl.l_len = 0;
	return (fcntl(fd,F_SETLK,&fl));
}
bool already_running()
{
	int fd;
	char buf[16];
	fd = open(LOCKFILE, O_RDWR|O_CREAT, LOCKMODE);
	if (fd < 0)
    {
		write_log("can't open %s: %s", LOCKFILE, strerror(errno));
		return true;
	}
	if (lockfile(fd) < 0)
    {
		if (errno == EACCES || errno == EAGAIN)
		{
			close(fd);
			return true;
		}
		write_log("can't lock %s: %s", LOCKFILE, strerror(errno));
		return true;
	}
	ftruncate(fd, 0);
	sprintf(buf,"%d", getpid());
	write(fd,buf,strlen(buf)+1);
	return false;
}
bool daemon_init(void)
 {
     setsid();
     umask(0); /* clear file mode creation mask */
     close(0); /* close stdin */
     close(1); /* close stdout */
     close(2); /* close stderr */
     return(true);
}
void canhbao(char * mahang, int gmua,int gban)
{
    char cmd[200];
    sprintf(cmd,"/usr/bin/canhbao %s %d %d",mahang,gmua,gban);
    system(cmd);
}
void post_blog()
{
    system("/usr/bin/postblog");
}
void themgia(char * mahang,int giamua, int giaban)
{
	char sql[500];
    sprintf(sql,"insert into g_banggia (gia_mahang,gia_mua,gia_ban,gia_time) value ('%s','%d','%d',NOW());",mahang,giamua,giaban);
    write_log(sql);
    executesql(sql);
	isnew=true;
}

void gvang()
{
    shtml sh,tr,td;
    int gia[2],i,id=0;
	isnew=false;
    if (!sh.loadFromURL("http://vip.giavang.net/data/GoldenPrice.php")) return;
    sh.retainTagByName("table");
    sh.removeTagByName("tr",3);
    tr=sh.cutTagByName("tr");
    /*
    for (i=0;i<2;i++)
    {
        td=tr.cutTagByName("td");
        td.removeAllTags();
        gia[i]=td.toInt();
    }
    themgia("GOLDTG",gia[0],gia[1]);
    */
    sh.removeTagByName("tr",3);
    tr=sh.cutTagByName("tr");
    //write_log("tr%d %s",id,tr.getContent().c_str());
    tr.removeTagByName("td");
    for (i=0;i<2;i++)
    {
        td=tr.cutTagByName("td");
        td.removeAllTags();
        td.replace(",","",-1);
        gia[i]=td.toInt();
        if (gia[i]>1000) gia[i]=(int)(gia[i]/1000);
    }
    if ((giasp[id][1]==0)||(gia[0]!=giasp[id][0])||(gia[1]!=giasp[id][1]))
    {
        themgia("SJCHCM",gia[0],gia[1]);
        canhbao("SJCHCM",gia[0],gia[1]);
        /*
        if ((baogia==0)||(abs(gia[1]-baogia)>=100000))
        {
            canhbao(gia[0],gia[1]);
            baogia=gia[1];
        }
        */
        giasp[id][0]=gia[0];
        giasp[id][1]=gia[1];
    }
    id++;
    tr=sh.cutTagByName("tr");
    //write_log("tr%d %s",id,tr.getContent().c_str());
    tr.removeTagByName("td");
    for (i=0;i<2;i++)
    {
        td=tr.cutTagByName("td");
        td.removeAllTags();
        td.replace(",","",-1);
        gia[i]=td.toInt();
        if (gia[i]>1000) gia[i]=(int)(gia[i]/1000);
    }

    if ((giasp[id][1]==0)||(gia[0]!=giasp[id][0])||(gia[1]!=giasp[id][1]))
    {
        themgia("SJCMBAC",gia[0],gia[1]);
        giasp[id][0]=gia[0];
        giasp[id][1]=gia[1];
    }
    id++;
	if (isnew)
	{
		post_blog();
	}

}
int main(int argc, char** argv)
{
    struct tm *sTm;
	time_t now;
	if (argc>2) DEBUG=true;
    if (!DEBUG) daemon_init();
    if (already_running())
    {
        write_log("Giavang is already running!");
        return 1;
    }
	init_mysql_conf();
    signal(SIGQUIT,call_for_exit);
	signal(SIGKILL,call_for_exit);
	signal(SIGTERM,call_for_exit);
    //signal(SIGHUP,reload);
    while (!STOP)
    {
		if (init_mysql())
        {
            gvang();
            system("/usr/bin/laytin");
        }

		now = time (0);
		sTm = gmtime (&now);
		sleep_time= ( (sTm->tm_hour >=15) || (sTm->tm_hour <= 2) ) ? 7200:600;
        sleep(sleep_time);
    }

    return 0;
}
